require ("webif2.addon.string")
util = require("webif2.xwrt.util")

local hcat = io.open("/tmp/.webcache/cat_root","r")
local hsub = io.open("/tmp/.webcache/subcat_root","r")
local tmenu = {}
if hsub then
for line in hsub:lines() do
	local _, _, cat, ord, sub, link = string.find(line, "([^:]*):([^:]*):([^:]*):(.*)")
--	print(cat, ord, sub, link)
	if tmenu[cat] == nil then tmenu[cat] = {} end
	if tmenu[cat][ord] == nil then tmenu[cat][ord] = {} end
	tmenu[cat][ord][sub] = link
end
end
local strhtml = ""
local xwrtmenu = ""
if hcat then
	xwrtmenu = xwrtmenu..'\t<ul id="menuitem">\r\n'
	for line in hcat:lines() do
		local _, _, cat, link = string.find(line, "([^:]*):(.*)")
		if tmenu[cat] then
			xwrtmenu = xwrtmenu.."\t\t\t<li><a href=\""..link.."\" >"..cat.."</a>"

			xwrtmenu = xwrtmenu..'\r\n\t\t\t<ul id="menusubitem">\r\n'
			for ord, tsub in util.pairsByKeys(tmenu[cat]) do
				if tsub then
					for sub, slink in pairs(tsub) do
						xwrtmenu = xwrtmenu.."\t\t\t\t<li><a href=\""..slink.."\">"..sub.."</a></li>\r\n"
					end
				end
			end
			xwrtmenu = xwrtmenu..'\r\n\t\t\t</ul>\r\n'

			xwrtmenu = xwrtmenu.."\t\t\t</li>\r\n"
		end
	end
	xwrtmenu = xwrtmenu..'\t\t</ul>\r\n'
end
strhtml = strhtml..[[
<div id="navcontainer">
	<ul id="navlist">
		<li><a href="#">Aplications</a>
	]]..xwrtmenu..[[
		</li>
	</ul>
</div>
]]
print(strhtml)
--	print(json.encode({status=t}).."\r\n\r\n")
--end